package crawler.kairui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import util.HttpConnectionGet;
import util.MybatisTool;

public class QiRuiQiCheCrawler {
	public List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		try {
			String getPro = "https://dealer.karryauto.cn/api-basic/api/region/findAllProvinces";
			// 获取省份
			String proStr = HttpConnectionGet.getJson(getPro);
			JSONArray provinces = JSON.parseArray(proStr);
			for (int i = 0; i < provinces.size(); i++) {
				JSONObject province = provinces.getJSONObject(i);
				String proNum = province.getString("id");
				String proName = province.getString("name");

				String getCity = "https://dealer.karryauto.cn/api-basic/api/region/findCityByProvinceId/" + proNum;
				String cityStr = HttpConnectionGet.getJson(getCity);
				JSONArray citys = JSON.parseArray(cityStr);
				for (int j = 0; j < citys.size(); j++) {
					JSONObject city = citys.getJSONObject(j);
					String cityNum = city.getString("id");
					String cityName = city.getString("name");

					String getDealer = "https://dealer.karryauto.cn/api-dealer/dealer-info/searchDealerListByCondition";
					String param = "{\"brandId\":\"f634f2a1-2d8a-4625-b1b1-6b8fb54d0327\",\"provinceId\":" + proNum
							+ ",\"cityId\":" + cityNum
							+ ",\"seriesId\":\"\",\"abbreviation\":\"\",\"enabledFlag\":1,\"type\":\"1\"}";
					String dealerStr = getPostJson(getDealer, param);
					JSONArray dealers = JSON.parseObject(dealerStr).getJSONArray("data");
					for (int k = 0; k < dealers.size(); k++) {
						JSONObject dealer = dealers.getJSONObject(k);
						String name = dealer.getString("name");
						String address = dealer.getString("address");
						String sellTell = dealer.getString("salesTel");
						String warpLatitude = dealer.getString("warpLatitude");
						String[] lngAndLat = null;
						if (warpLatitude != null) {
							lngAndLat = warpLatitude.split(",");
						}
						String lng = null;
						String lat = null;
						if (lngAndLat != null && lngAndLat.length == 2) {
							lng = lngAndLat[0];
							lat = lngAndLat[1];
						}

						AgencyEntity agency = new AgencyEntity();
						agency.setdCloseDate(null);
						agency.setdOpeningDate(null);
						agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
						agency.setnBrandID(-1);
						agency.setsBrand("开瑞");

						agency.setnDealerIDWeb(-1);
						agency.setnManufacturerID(-1);
						agency.setsManufacturer("奇瑞汽车");

						agency.setnState(1);
						agency.setsAddress(address);
						agency.setsCity(cityName);
						agency.setsCustomerServiceCall(null);
						agency.setsDealerName(name);
						agency.setsDealerType("经销商");
						agency.setsProvince(proName);
						agency.setsSaleCall(sellTell);
						agency.setsLongitude(lng);
						agency.setsLatitude(lat);
						list.add(agency);

					}

				}

			}

		} catch (Exception e) {
			throw new RuntimeException("爬虫异常", e);
		}

		return list;
	}

	String getPostJson(String path, String param) {
		PrintWriter pw = null;
		BufferedReader br = null;
		try {
			URL url = new URL(path);
			URLConnection urlConn = url.openConnection();
			HttpURLConnection conn = (HttpURLConnection) urlConn;
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);// 不允许缓存
			conn.setRequestMethod("POST");// 设置请求方式,默认为get

			conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("user-agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
			conn.connect();// 可以省了,使用下面的urlConn.getOutputStream()会自动connect
			// 建立输出流，向指向的URL传入参数
			pw = new PrintWriter(conn.getOutputStream());
			pw.print(param);
			pw.flush();
			// 建立输入流,读取返回的信息
			br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null; // 每行内容
			StringBuffer content = new StringBuffer();
			while ((line = br.readLine()) != null) {
				content.append(line);
			}
			// System.out.println(content);
			return content.toString();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (pw != null & br != null) {
				pw.close();
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return null;
	}

	public static void main(String[] args) {
		QiRuiQiCheCrawler crawler = new QiRuiQiCheCrawler();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for (AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");

	}

}
